<template>
  <div id="knowledge-info-page" class="knowledge-info-box">
    <mobileNavbar :name="titleName" :showBottomBorder="true" @back="handleBack" :isBackPath="knowledgeList.length<=1">
      <template v-slot:right>
        <svg class="sort-svg-icon" aria-hidden="true" @click="openSort">
          <use xlink:href="#keowledge-mobile-shaixuan"></use>
        </svg>
      </template>
    </mobileNavbar>
    <div class="lately-list" v-loading="loading">
      <mobileScroll :ops="scrollOps" v-if="fileList.length!=0"  ref="mobileScrollRef" :openPullDown="true" :openUpload="false" @refreshStart="handleRS">
        <div v-for="(item,index) in fileList" :key="index" class="lately-item" @click="openItem(item)">
          <div class="lately-item-icon">
            <svg class="icon" aria-hidden="true">
              <use v-bind:xlink:href="getIcon(item.type,item.nameSuffix)"></use>
            </svg>
          </div>
          <div class="lately-item-content">
            <div class="content">
              <div class="name">{{item.name}}</div>
              <div class="time">{{item.createTime}}</div>
            </div>
            <div class="lately-actions">
              <svg class="action-icon" aria-hidden="true" v-if="item.share">
                <use xlink:href="#keowledge-mobile-fenxiang-xianshi"></use>
              </svg>
              <svg class="action-icon" aria-hidden="true" v-if="item.type!='knowledge'&&item.type!='directory'" @click.stop="docStar(item)">
                <use v-bind:xlink:href="`#${item.collectIs?'keowledge-mobile-shoucang-xuanzhong-2':'keowledge-mobile-shoucang-weixuanzhong-2'}`"></use>
              </svg>
              <svg class="action-icon" aria-hidden="true" @click.stop="openActions(item)">
                <use xlink:href="#keowledge-mobile-gengduocaozuo"></use>
              </svg>
            </div>
          </div>
        </div>
      </mobileScroll>
      <jvs-empty imgSrc="@/assets/images/common/empty.png" v-if="fileList.length==0"></jvs-empty>
    </div>
    <moreAction ref="moreActionRef" @doAction="doAction"></moreAction>
    <sortAction ref="sortActionRef" :showType="false" @cancal="handleCancal" @submit="handleSubmit"></sortAction>
    <shareBox ref="shareBoxRef" @changeShareType="changeShareType"></shareBox>
    <addTag ref="addTagRef"></addTag>
    <confirmBox :visible="reNameVisible" ref="reNameConfirmBox" @handleSubmit="submitRename" @handleClose="closeRename" :isModelClose="false"
      :title="$t('message.buttons.reName')">
      <template  v-slot:content>
        <div class="rename-content">
          <el-input v-model="currentOpenItem.name" :placeholder="$t('message.placeholder.pleaseFileNames')" maxlength="128"></el-input>
        </div>
      </template>
    </confirmBox>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance
} from 'vue' 
import type {ComponentInternalInstance} from 'vue'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import mobileNavbar from './mobileNavbar.vue';
import moreAction from './moreAction.vue'
import sortAction from './sortAction.vue'
import addTag from './addTag.vue'
import confirmBox from './confirmBox.vue'
import shareBox from './shareBox.vue'
import mobileScroll from './mobileScroll.vue'
import { getLibTree,dclibRecycle,fileTreeSort } from "@/api/knowledge";
import { setLibrary,docStar } from '@/api/common'
import { setSessionStore,getSessionStore } from '@/utils/store.js'
import { useRoute, useRouter } from "vue-router"
const router = useRouter();
const route = useRoute()
const emit = defineEmits([""])
const props = defineProps({

})

const titleName = ref('')
const fileList = ref([])
const konwledgeInfo = ref({})
const scrollOps = ref({
  click:true,
  observeDOM: true,
  probeType: 3,
  pullDownRefresh: {
    threshold: parseFloat(document.documentElement.style.fontSize) * 6.25,
    stop:  parseFloat(document.documentElement.style.fontSize) * 6.25
  },
  pullUpLoad: true,
  bounce:{
    top:false,
    bottom:false
  }
})
const sortObj =ref({
  type:"",
  sort:'createTime,true',
})
const currentOpenItem = ref({})
const reNameVisible = ref(false)
const knowledgeList = ref([])
const loading = ref(false)
const moreActionRef = ref()
const sortActionRef = ref()
const shareBoxRef = ref()
const addTagRef = ref()
const mobileScrollRef = ref()
onMounted(()=>{
  knowledgeList.value =  getSessionStore({name:'mobileKnowledgeList'}) || []
  if(knowledgeList.value.length<=1){
    knowledgeList.value.push(route.query.id)
    init(route.query.id)
  }else{
    init(knowledgeList.value[knowledgeList.value.length-1])
  }
})

function init(id,done){
  if(!done){
    loading.value = true
    mobileScrollRef.value?.updateScroll()
  }
  getLibTree({
    id:id
  }).then(res=>{
    if(res.data.code==0){
      fileList.value = res.data.data.data
      konwledgeInfo.value = Object.assign({},konwledgeInfo.value,res.data.data.dcLibrary)
      titleName.value = konwledgeInfo.value.name
      loading.value = false
      if(done) done()
    }
  })
}
function handleRS(done){
  init(konwledgeInfo.value.id,done,true)
}
function handleBack(val){
  if(val){
    setSessionStore({name:'mobileKnowledgeList',content:[]})
    router.push(val)
  }else{
    knowledgeList.value.pop()
    setSessionStore({name:'mobileKnowledgeList',content:knowledgeList.value})
    init(knowledgeList.value[knowledgeList.value.length-1])
  }
}
function openActions(item){
  currentOpenItem.value = JSON.parse(JSON.stringify(item))
  moreActionRef.value.openActions(item)
}
function openSort(){
  sortActionRef.value.openSort(sortObj.value)
}
function openShare(){
  shareBoxRef.value.openShare(currentOpenItem.value)
}
function doAction(item){
  switch (item.method) {
    case 'addTag':
      moreActionRef.value.closeActions()
      addTagRef.value.openActions(currentOpenItem.value)
      break;
    case 'move':
      moreActionRef.value.closeActions()
      setSessionStore({name:'moveFile',content:currentOpenItem.value})
      let routerList = getSessionStore({name:'mobileRouterList'}) || []
      let currentPath = route.fullPath
      if(routerList.indexOf(currentPath)!=-1){
        routerList.splice(routerList.indexOf(currentPath),1)
      }
      routerList.push(currentPath)
      setSessionStore({name:'mobileRouterList',content:routerList})
      router.push('/mobile/movefile')
      break;
    case 'share':
      moreActionRef.value.closeActions()
      openShare()
      break;
    case 'reName':
      reNameVisible.value  = true
      moreActionRef.value.closeActions()
      break;
    case 'del':
      moreActionRef.value.closeActions()
      proxy.$mobileConfirm({
        text:currentOpenItem.value.type=='directory'?$t('message.confirm.sureDeleteMenu'):$t('message.confirm.delFielContent'),
        cancal(callBack){
          callBack && callBack()
        },
        submit(){
          dclibRecycle(currentOpenItem.value.id).then(res=>{
            if(res.data.code==0){
              proxy.$mobileMessage({
                text:$t('message.message.moveRecycle'),
                type:'success'
              })
              init(konwledgeInfo.value.id)
            }
          })
        }
      })
      break
    case 'copy':
      const copyText = async (val,callback) => {
        if (navigator.clipboard && navigator.permissions) {
          await navigator.clipboard.writeText(val)
          if(callback) callback()
        } else {
          const textArea = document.createElement('textArea')
          textArea.value = val
          textArea.style.width = 0
          textArea.style.position = 'fixed'
          textArea.style.left = '-999px'
          textArea.style.top = '10px'
          textArea.setAttribute('readonly', 'readonly')
          document.body.appendChild(textArea)
          textArea.select()
          document.execCommand('copy')
          document.body.removeChild(textArea)
          if(callback) callback()
        }
      }
      copyText(window.location.origin+`/#/view?id=${_self.currentOpenItem.knowledgeId}&docId=${_self.currentOpenItem.id}&type=${_self.currentOpenItem.type}`,()=>{
        moreActionRef.value.closeActions()
        proxy.$mobileMessage({
          text:$t('message.message.copySuccess'),
          type:'success'
        })
      })
      break
    default:
      break;
  }
}
function docStar(item){
  docStar(item.id).then(res=>{
    if(res.data.code==0){
      proxy.$mobileMessage({
        text:item.collectIs?$t('message.message.cancelCollectSuccess'):$t('message.message.addCollectSuccess'),
        type:'success'
      })
      item.collectIs = !item.collectIs
      // this.$forceUpdate()
      // this.init(konwledgeInfo.value.id)
    }
  })
}
function submitRename(){
  setLibrary(currentOpenItem.value).then(res=>{
    if(res.data.code == 0){
      proxy.$mobileMessage({
        text:$t('message.message.editNameSuccess'),
        type:'success'
      })
      init(konwledgeInfo.value.id)
      closeRename()
    }
  }).catch(err=>{
    closeRename()
  })
}
function closeRename(){
  reNameVisible.value = false
}
function openItem(item){
  if(item.type=="directory"){
    knowledgeList.value.push(item.id)
    setSessionStore({name:'mobileKnowledgeList',content:knowledgeList.value})
    init(item.id)
  }else{
    let routerList = getSessionStore({name:'mobileRouterList'}) || []
    let currentPath = route.fullPath
    if(routerList.indexOf(currentPath)!=-1){
      routerList.splice(routerList.indexOf(currentPath),1)
    }
    routerList.push(currentPath)
    setSessionStore({name:'mobileRouterList',content:routerList})
    router.push({
      path:'/mobile/viewfile',
      query:{
        knId:item.knowledgeId,
        type:item.type,
        docId:item.id,
        nameSuffix:item.nameSuffix||'',
        fileName:item.name||item.dcName
      }
    })
  }
}
function changeShareType(item){
  currentOpenItem.value.share = item
  fileList.value.forEach((i)=>{
    if(i.id==currentOpenItem.value.id){
      i.share = item
    }
  })
}
function handleSubmit(obj){
  sortObj.value = obj
  const type  = sortObj.value.sort.split(',')[0],checkStatus = eval(sortObj.value.sort.split(',')[1])
  fileTreeSort({
      sortName:type,
      id:route.query.id,
      isSortDesc:checkStatus
  }).then(res=>{
      if(res.data.code==0){
        proxy.$mobileMessage({
          text:$t('message.message.sortSuccess'),
          type:'success'
        })
        init(konwledgeInfo.value.id)
      }
  })
}
function handleCancal(){

}

</script>
<style lang="scss" scoped>
.knowledge-info-box{
  position: relative;
  height: 100%;
  .sort-svg-icon{
    width: 1.125rem;
    height: 1.125rem;
  }
  .lately-list{
      height: calc(100% - 3.125rem);
      // overflow-y: auto;
      .lately-item{
        display: flex;
        align-items: center;
        padding: 0px 0px 0px .9375rem;
        .lately-item-icon{
          height: 4.25rem;
          display: flex;
          align-items: center;
          .icon{
            height: 1.375rem;
            width: 1.375rem;
          }
        }
        .lately-item-content{
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-left: .75rem;
          width: calc(100% - 2.125rem);
          padding-right: .9375rem;
          height: 4.25rem;
          border-bottom: .0625rem solid #eeeff0;
          .content{
            font-size: .9375rem;
            font-weight: 400;
            color: #363B4C;
            .name{
              @include SourceHanSansCN-Medium;
              margin-bottom: .25rem;
              max-width: 14.5rem;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
            .time{
              font-size: .875rem;
              font-weight: 400;
              color: #6f7588;
              @include SourceHanSansCN-Regular;
            }
          }
          .lately-actions{
            .action-icon{
              height: 1.375rem;
              width: 1.375rem;
            }
            .action-icon+.action-icon{
              margin-left: .75rem;
            }
          }
        }
      }
  }
}
.rename-content{
  width: 100%;
  height: 2.5rem;
  display: flex;
  align-items: center;
  margin-bottom: .75rem;
  margin-left: .75rem;
  margin-right: .75rem;
  ::v-deep(input){
    border: none;
    background-color: transparent;
  }
  background: #F5F6F7;
  border-radius: .25rem;
}
</style>